package com.webserver.servlet;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Arrays;

public class Change_Password extends HttpServlet{
    public void service(HttpRequest httpRequest, HttpResponse httpResponse) {
        //读取
        String username = httpRequest.getQueryMap("username");
        String password = httpRequest.getQueryMap("password");
        String npw1 = httpRequest.getQueryMap("newpassword");
        String npw2 = httpRequest.getQueryMap("newpassword1");
        try(RandomAccessFile raf = new RandomAccessFile("user.dat","rw")) {
            for (int i = 0; i < raf.length() / 100; i++) {
                raf.seek(i * 100);//移动指针到每条记录的开始位置
                byte[] data = new byte[32];
                raf.read(data);
                String name = new String(data, "UTF-8").trim();
                if (name.equals(username)) {
                    raf.read(data);
                    String pw = new String(data, "UTF-8").trim();
                    if (pw.equals(password)) {
                        if (npw1.equals(npw2)) {
                            raf.seek(i * 100+32);
                            data = npw1.getBytes("UTF-8");
                            raf.write(data);
                            httpResponse.setFile(new File("./Webapps/myweb/change_success.html"));
                            return;
                        }
                    }
                    break;
                }
            }
            httpResponse.setFile(new File("./Webapps/myweb/error.html"));
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("修改成功");
    }
}
